"""模拟线程不安全
    虽然python有GIL，但是在进行多线程时还是需要考虑线程安全的问题，因为GIL是时间片机制，每个线程都可以获得一段时间的执行时间，
而线程锁则是在没有释放锁之前，cpu只能执行当前线程
"""

import threading


def job1():
    global n
    for i in range(10):
        n += 1
        print('job1', n)


def job2():
    global n
    for i in range(10):
        n += 10
        print('job2', n)


def job3():
    global n, lock
    # 获取锁
    lock.acquire()
    for i in range(10):
        n += 1
        print('job1', n)
    lock.release()


def job4():
    global n, lock
    # 获取锁
    lock.acquire()
    for i in range(10):
        n += 10
        print('job2', n)
    lock.release()


n = 0
# 不加锁
t1 = threading.Thread(target=job1)
t2 = threading.Thread(target=job2)
# t1.start()
# t2.start()

# 加锁
lock = threading.Lock()
t3 = threading.Thread(target=job3)
t4 = threading.Thread(target=job4)
t3.start()
t4.start()
